package com.ssy.lingxi.order.serviceimpl.feign;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.contract.api.model.constant.ContractConstants;
import com.ssy.lingxi.contract.api.model.vo.request.ContractOrderAmountLogRequest;
import com.ssy.lingxi.contract.api.model.vo.request.ContractOrderMaterielRequest;
import com.ssy.lingxi.order.model.dto.OrderProductDTO;
import com.ssy.lingxi.order.service.feign.IContractFeignService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同服务Feign接口调用实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-08-26
 */
@Service
public class ContractFeignServiceImpl implements IContractFeignService {
    private static final Logger logger = LoggerFactory.getLogger(ContractFeignServiceImpl.class);

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 合同订单（SRM订单）创建后，向合同服务同步订单数据
     *
     * @param orderId     订单Id
     * @param totalAmount 订单金额
     * @param contractId  合同Id
     * @param products    商品信息列表
     */
    @Override
    public void createSrmOrderAsync(Long orderId, BigDecimal totalAmount, Long contractId, List<OrderProductDTO> products) {
        srmOrderAsync(orderId, totalAmount, contractId, 1, products);
    }

    /**
     * 合同订单（SRM订单）取消后，向合同服务同步订单数据
     *
     * @param orderId     订单Id
     * @param totalAmount 订单金额
     * @param contractId  合同Id
     * @param products    商品信息列表
     */
    @Override
    public void cancelSrmOrderAsync(Long orderId, BigDecimal totalAmount, Long contractId, List<OrderProductDTO> products) {
        srmOrderAsync(orderId, totalAmount, contractId, 2, products);
    }

    /**
     * 向合同服务同步Srm订单数据
     *
     * @param orderId     订单Id
     * @param totalAmount 订单金额
     * @param contractId  合同Id
     * @param type        类型：1-创建订单，2-取消订单
     * @param products    商品信息列表
     */
    @Async
    @Override
    public void srmOrderAsync(Long orderId, BigDecimal totalAmount, Long contractId, Integer type, List<OrderProductDTO> products) {
        ContractOrderAmountLogRequest request = new ContractOrderAmountLogRequest();
        request.setContractId(contractId);
        request.setOrderId(orderId);
        request.setSumPrice(totalAmount.doubleValue());
        request.setType(type);
        request.setContractOrderMaterielRequestList(products.stream().map(p -> {
            ContractOrderMaterielRequest materielRequest = new ContractOrderMaterielRequest();
            materielRequest.setAssociatedDataId(p.getProductId());
            materielRequest.setAssociatedMaterielNo(p.getProductNo());
            materielRequest.setCount(p.getQuantity().doubleValue());
            return materielRequest;
        }).collect(Collectors.toList()));

        try {
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(request);
            logger.info("向合同服务发送消息：" + json);
            rabbitTemplate.convertAndSend(ContractConstants.CONTRACT_ORDER_CHANGE_EXCHANGE, ContractConstants.CONTRACT_ORDER_CHANGE_ROUTINGKEY, json);
        } catch (Exception e) {
            logger.error("向合同服务发送mq消息错误：" + e.getMessage());
        }
    }
}
